package com.example.java_gobang.game;

import com.example.java_gobang.model.Room;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

//房间管理类,这个类也希望有唯一的实例
@Component
public class RoomManager {
    //房间id到房间的映射
    private ConcurrentHashMap<String, Room>rooms=new ConcurrentHashMap<>();
    //用户id到房间id的映射
    private ConcurrentHashMap<Integer,String>userIdToRoomId=new ConcurrentHashMap<>();

    //加入房间
    public void add(Room room,int userId1,int userId2){
        rooms.put(room.getRoomId(),room);
        userIdToRoomId.put(userId1,room.getRoomId());
        userIdToRoomId.put(userId2,room.getRoomId());
    }

    //退出房间
    public void remove(String roomId,int userId1,int userId2){
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    //获取房间的信息
    public Room getRoomByRoomId(String roomId){
       return rooms.get(roomId);
    }

    //根据玩家id来获取房间
    public Room getRoomByUserId(int userId){
        String roomId=userIdToRoomId.get(userId);
        if(roomId==null){
            //没有找到房间
            return null;
        }
        return rooms.get(roomId);
    }
}
